package com.gbase8c.dmt.migration.job;

import com.gbase8c.dmt.common.util.Exceptions;
import com.gbase8c.dmt.migration.MoLogger;
import com.gbase8c.dmt.model.enums.MigrationObjectType;
import com.gbase8c.dmt.model.migration.dto.MigrationObject;
import com.gbase8c.dmt.model.migration.record.JobThreadRecord;
import com.gbase8c.dmt.model.enums.Status;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.QueryRunner;

import javax.sql.DataSource;
import java.util.List;

@Slf4j
public class TableJobThread extends AbstractJobThread {

    public TableJobThread(MigrationObjectType type, MigrationObject dbObject, DataSource tarDataSource, MoLogger moLogger) {
        super(type, dbObject, tarDataSource, moLogger);
    }

    @Override
    public JobThreadRecord call(){
        JobThreadRecord jobThreadRecord = new JobThreadRecord();
        try {
            //todo:添加convert转换成功与否判断
            QueryRunner queryRunner = new QueryRunner(this.tarDataSource);
            List<String> contents = dbObject.getContents();
            jobThreadRecord.setSchemaName(dbObject.getSchema());
            for (String sql:contents){
                int execute = queryRunner.execute(sql);
                log.info("sql:{} \n 执行结果: {}",sql,execute);
            }
            dbObject.setStatus(Status.Finished);
            jobThreadRecord.setFlag(true);
        }catch (Exception exception) {
            String errorLog = Exceptions.getStackTraceAsString(exception);
            dbObject.setMsg(exception.getMessage());
            jobThreadRecord.setFlag(false);
            jobThreadRecord.setErrorLog(errorLog);
        }
        jobThreadRecord.setDbObject(dbObject);
        return jobThreadRecord;
    }
}
